package day_17.ChengYuanBianLiang;

import java.lang.reflect.Field;

public class ReflectDemo2 {
    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        //M1();
        M2();
    }

    private static void M2() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //1.获取class对象
        Class aClass = Class.forName("day_17.ChengYuanBianLiang.Student");
        //2.获取成员变量Field的对象
        Field field = aClass.getDeclaredField("money");
        //3.取消一下访问检查
        field.setAccessible(true);
        //4.调用get方法来获取值
        //4.1创建一个对象
        Student student =(Student) aClass.newInstance();
        //4.2获取指定对象的money的值
        Object o = field.get(student);
        //5.打印一下
        System.out.println(o);
    }

    private static void M1() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //        void set(Object obj, Object value)：给obj对象的成员变量赋值为value
        //1.获取class对象
        Class aClass = Class.forName("day_17.ChengYuanBianLiang.Student");
        //2.获取name这个Field对象
        Field field = aClass.getField("name");
        //3.利用set方法进行赋值.
        //3.1先创建一个Student对象
        Student student =(Student)aClass.newInstance();
        //3.2有了对象才可以给指定对象进行赋值
        field.set(student,"杜某");
        System.out.println(student);

    }
}
class lx02{
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        //m1();
        m2();
    }

    private static void m2() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class aClass = Class.forName("day_17.ChengYuanBianLiang.Student");
        Field field = aClass.getDeclaredField("money");
        field.setAccessible(true);
        Student student1 =(Student) aClass.newInstance();
        Object o = field.get(student1);
        System.out.println(o);
    }

    private static void m1() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class aClass = Class.forName("day_17.ChengYuanBianLiang.Student");
        Field field = aClass.getField("name");
        Student student =(Student) aClass.newInstance();
        field.set(student,"李某");
        System.out.println(student);
    }
}
